﻿using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace HealthCheck.Api.HealthChecks;

public class ExternalApiHealthCheck
	(IHttpClientFactory httpClientFactory, 
		IConfiguration configuration)
	: IHealthCheck
{
	public async Task<HealthCheckResult> CheckHealthAsync(
		HealthCheckContext context, 
		CancellationToken cancellationToken = default)
	{
		var apiUrl = configuration["ExternalApi:HealthCheckUrl"] ?? "https://httpbin.org/get";
		try
		{
			var client = httpClientFactory.CreateClient();
			var response = await client.GetAsync(apiUrl, cancellationToken);
			if (response.IsSuccessStatusCode)
			{
				return HealthCheckResult.Healthy($"外部API响应正常: {response.StatusCode}");
			}
			return HealthCheckResult.Degraded($"外部API响应异常: {response.StatusCode}");
		}
		catch (Exception ex)
		{
			return HealthCheckResult.Unhealthy($"外部API检查失败: {ex.Message}");
		}
	}
}
